/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Navbar,
    Toolbar,
    Text,
    Button,
    IconButton,
    MenuList,
    MenuItem,
    useTheme,
    useToast,
    LayerLoading,
    Container,
    IconMoreVertical,
    IconArrowLeft,
    IconArrowRight,
    IconPackage,
    IconRefButton,
    Select,
    VerticalMenu,
    DdMenuItem,
    TwoHalfRightPanel, PanelEnlargeCtx
} from "customize-easy-ui-component";
import { Link as RouterLink } from "../routing/Link";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";
import useCreateDeviceMutation from "./useCreateDeviceMutation";
import {css} from "@emotion/react";
import {设备品种, 设备种类, 设备类别} from "../dict/eqpComm";
import {ContainLine, TransparentInput} from "../comp/base";
import {DeviceClassSelect} from "./DeviceClassSelect";



interface NewDeviceProps {
    id?: string;
    readOnly?: boolean;
    dt?:any;
}
//接替DeviceCreate
const NewDevice: React.FunctionComponent<NewDeviceProps> = ({
                                                                readOnly,
                                                                id,
                                                                dt=null,
                                                            }) => {
    const theme = useTheme();
    const toast = useToast();
    const [editing, ] = React.useState(!readOnly|| true);
    const [ingredients, setIngredients] = React.useState<any>( dt||{} );
    const [eqp, setEqp] = React.useState(dt);    //为了更改数据用的。
    const {history } = useContext(RoutingContext);
    const {call:createEqpfunc,isInFlight, result:entry}= useCreateDeviceMutation();

    async function saveRecipe( a : any
    ) {
        try {
            //setLoading(true);
            console.log("baochun等待之前１ ingredients=", ingredients );
            //这时才去修改submitfunc参数，已经来不及，setOptions异步执行；submitfunc会看见前面的取值。
            //setOptions({oid:"test暂且空着",  ...ingredients});
            console.log("baochun等待之前２ ingredients=", ingredients );
            await createEqpfunc(a==='导入'? eqp?.cod? 'cod':'oid' : eqp?.type,
                { cod:dt?.cod, oid:dt?.oid, ...eqp});       //要等待正常的结果应答从后端返回。
            //submitfunc(); 立刻执行后面代码，这样不会等待后端应答的。
            /*点击函数发送给后端服务器，即刻返回到这里了await submitfunc();　这个时候entry还不是后端的应答数据，要等到下一次entry被ＨＯＯＫ修正*/
            //  console.log("等半天createEntry返回error=",error,"结果",entry );

            //加了await 后的　submitfunc();似乎也不能确保entry非空的，必须等待下一次render()。
            //    entry && setLocation("/device/" + entry.id, { replace: true } );
            //原型是 PushCallback = (to: Path, replace?: boolean) => void;
        } catch (err: any) {
            //setLoading(false);
            toast({
                title: "捕获errcc错",
                subtitle: err.message,
                intent: "error"
            });
            console.log("捕获err打了吗", err);
        }
    }

    //保存 编辑新的设备之后，要修正URL
    React.useEffect(() => {
        entry && ( history.push("/device/" + entry));
    }, [entry, history]);

    const {enlarge, setEnlarge,  setActivecas } =useContext(PanelEnlargeCtx);

    return (
        <TwoHalfRightPanel
            title={`新的设备设立`}
            back={
                <RouterLink href={`/device`}>
                    <IconButton  noBind  icon={<IconArrowLeft />}
                                 variant="ghost"
                                 label="后退"
                                 size="md"
                                 css={{
                                     marginRight: theme.spaces.sm,
                                     [theme.mediaQueries.md]: {
                                         display: "none"
                                     }
                                 }}
                    />
                </RouterLink>
            }
            menu={
                <VerticalMenu>
                    <DdMenuItem label="功能待续"
                                onClick={(e) => {
                                }}/>
                </VerticalMenu>
            }
        >

        <Container>

            <div
                css={{
                    paddingTop: theme.spaces.lg,
                    paddingBottom: theme.spaces.lg
                }}
            >
                {ingredients && (
                    <div>
                        <Text variant="h5">设备明细信息</Text>

                        <div>
                            <div>
                                <ContainLine display={'设备号'}>
                                    <TransparentInput
                                        placeholder="那一台电梯？"
                                        value={eqp?.cod || ''}
                                        onChange={e => setEqp({...eqp, cod: e.currentTarget.value||undefined}) }
                                    />
                                </ContainLine>
                                <ContainLine display={'监察识别码'}>
                                    <TransparentInput    autoFocus={true}
                                        placeholder="导入的情形可以不填写"
                                        value={eqp?.oid || ''}
                                        onChange={e => setEqp({...eqp, oid: e.currentTarget.value||undefined}) }
                                    />
                                </ContainLine>
                            </div>
                            <br/>
                            <Text>本平台设备库和其他平台的设备库的信息同步方式和注意事项请看说明手册</Text>
                            <DeviceClassSelect  eqp={eqp} setSelectClass={setEqp} />
                        </div>
                    </div>
                )}

                {editing && <Button
                    intent="primary"
                    disabled={false}
                    css={{ marginLeft: theme.spaces.sm }}
                    onPress={() => {  //按钮里面看不到最新的input取值的。
                        saveRecipe(null);
                    }}
                >
                    生成新设备
                </Button>
                }
                {editing && <Button
                    intent="primary"
                    disabled={false}
                    css={{ marginLeft: theme.spaces.sm }}
                    onPress={() => {  //按钮里面看不到最新的input取值的。
                        setActivecas(0);
                        // saveRecipe('导入');
                    }}
                >
                  导入旧平台设备
                </Button>
                }
            </div>

        </Container>

        </TwoHalfRightPanel>
    );
};


export default NewDevice;
